#include "PlayState.h"
#include "TextureManager.h"
#include "Game.h"
#include "Player.h"
//#include "Enemy.h"
//#include "PauseState.h"
#include "InputHandler.h"
//#include "GameOverState.h"
#include "StateParser.h"
#include "LevelParser.h"

const std::string PlayState::s_playID = "PLAY";

void PlayState::update(){
    m_pLevel->update();
#if 0
    if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_ESCAPE)){
   //     TheGame::Instance()->getStateMachine()
   //                        ->pushState(new PauseState());
    }

    for(int i = 0; i < m_gameObjects.size(); i++){
        m_gameObjects[i]->update();
    }
#endif
#if 0
    if(checkCollision(
                dynamic_cast<SDLGameObject*>(m_gameObjects[0]),
                dynamic_cast<SDLGameObject*>(m_gameObjects[1])
                )){
        std::cout << "happen collision" << std::endl;
//        TheGame::Instance()->getStateMachine()
//                           ->pushState(new GameOverState());
    }
#endif
}

void PlayState::render(){
    m_pLevel->render();
#if 0
    for(int i = 0; i < m_gameObjects.size(); i++){
        m_gameObjects[i]->draw();
    }
#endif
}

bool PlayState::onEnter(){
#if 0    
    StateParser stateParser;
    stateParser.parseState("assets/test.xml", 
                            s_playID,
                            &m_gameObjects,
                            &m_textureIDList);
#endif
    LevelParser levelParser;
    m_pLevel =  levelParser.parseLevel("assets/test_map1.tmx");

    std::cout << "entering PlayState" << std::endl;
    return true;
}

bool PlayState::onExit(){
    for (int i = 0; i < m_gameObjects.size(); i++){
        m_gameObjects[i]->clean();
    }
    m_gameObjects.clear();
//    TheTextureManager::Instance()->clearFromTextureMap("helipcopter");
    for (int i = 0; i < m_textureIDList.size(); i++){
        TheTextureManager::Instance()
            ->clearFromTextureMap(m_textureIDList[i]);
    }

    std::cout << "exiting PlayState" << std::endl;
    return true;
}

bool PlayState::checkCollision(SDLGameObject * player_1,
                               SDLGameObject * player_2){

    int leftA, leftB;
    int rightA, rightB;
    int topA, topB;
    int buttomA, buttomB;

    leftA = player_1->getPosition().getX();
    rightA = player_1->getPosition().getX() + player_1->getWidth();
    topA = player_1->getPosition().getY();
    buttomA = player_1->getPosition().getY() + player_1->getHeight();

     leftB = player_2->getPosition().getX();
    rightB = player_2->getPosition().getX() + player_2->getWidth();
    topB = player_2->getPosition().getY();
    buttomB = player_2->getPosition().getY() + player_2->getHeight();

    if (buttomA <= topB) { return false;}
    if (topA <= topB) { return false;}
    if (rightA <= leftB) {return false;}
    if (leftA >= rightB) { return false;}

    return true;
}

